package com.huoshan.im.server.service;

import com.huoshan.im.server.ContextNaming;
import com.huoshan.im.server.config.ConfigHolder;
import com.huoshan.im.server.config.properties.SettingConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 火山九日 on 2020-04-27 11:40
 */
@Slf4j
@Service
@AllArgsConstructor
public class ServerService {

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 这个缓存到redis提供给中转器使用的。外网ip对应关系需要运维提前准备。
     */
    public void cacheServerList() {
        List<String> cacheHostList = ConfigHolder.getLocalHostList();
        SettingConfig.Server server = ConfigHolder.getSettingConfig().getServer();
        for (String host : cacheHostList) {
            String key = String.format("%s:%s:%d", ContextNaming.REDIS_SERVER_LIST_PRE_KEY, host, server.getPort());
            log.info("注册server到缓存：{}:{}", host, server.getPort());
            redisTemplate.opsForValue().set(key, "", Duration.ofSeconds(120));
        }
    }

    public void clearServerList() {
        List<String> cacheHostList = ConfigHolder.getLocalHostList();
        SettingConfig.Server server = ConfigHolder.getSettingConfig().getServer();
        for (String host : cacheHostList) {
            String key = String.format("%s:%s:%d", ContextNaming.REDIS_SERVER_LIST_PRE_KEY, host, server.getPort());
            redisTemplate.delete(key);
        }
    }

}
